import datetime
import json
import threading
import re, os
import ast

import urllib3
from hashlib import sha1
from django.http.response import HttpResponse
from polls import models
from polls.grep.adb_views import dog, getDevicesAll, push
from polls.models import User
from polls.models import Test_Interface_List
from polls.models import Test_Interface_List_Content
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.csrf import ensure_csrf_cookie
from django.shortcuts import render
from django.core.cache import cache
import time, requests
from core.core import Core

# 登录
from untitled import settings
from PIL import Image

urllib3.disable_warnings()
ipconfig = os.popen("ipconfig")
ipconfig_list = [i.split("\n") for i in ipconfig]
if ipconfig_list[8] != ['', '']:
    ipconfig = ipconfig_list[8]
else:
    ipconfig = ipconfig_list[-3]

proxies = {"http": f"{ipconfig[0].split(':')[-1].replace(' ', '')}:8888"}


def index_login(request):
    if request.method == "POST":  # 判断请求为POST请求则是提交表单
        # User_user = User()  # 创建一个User实例
        username = request.GET.get("username")  # 获取提交表单中的name值，赋值给name
        password = request.GET.get("password")
        users = User.objects.all()
        for user in users:
            if user.username == username and user.password == password:
                return render(request, 'index_main.html')
    return render(request, 'login.html')


# 注册
def index_register(request):
    return render(request, 'register.html')


# 退出
def index_logout(request):
    if not request.session.get('is_login', None):
        # 如果本来就未登录，也就没有登出一说
        return render(request, 'login.html')
    request.session.flush()
    # 或者使用下面的方法
    # del request.session['is_login']
    # del request.session['user_id']
    # del request.session['user_name']
    return render(request, 'login.html')


# 首页
def index(request):
    return render(request, 'index_main.html')


# 注册—-存储
def user_mysql(request):
    if request.method == "GET":  # 判断请求为POST请求则是提交表单
        User_user = User()  # 创建一个User实例
        username = request.GET.get("username")  # 获取提交表单中的name值，赋值给name
        password = request.GET.get("password")
        gp = User.objects.filter(username=str(username))
        if len(gp) > 0:
            return HttpResponse('该账户已经存在')
        else:  # 获取提交表单中的age值，赋值给变量age
            User_user.username = username  # 把表单获取的username赋值给实例的username
            User_user.password = password  # 把表单获取的password赋值给实例的password
            User_user.save()  # 保存实例，把数据存到数据库
            return HttpResponse("用户已成功提交！")  # 保存成功给用户提示’
    else:
        return render(request, 'register.html')


# 第一排第一个
# web前端性能测试
def yellowlab_test(request):
    if request.method == 'POST':
        yellowlaburl = 'https://yellowlab.tools/api/runs'
        url = request.POST.get('url')
        if (re.match(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', url,
                     flags=0)) != None:

            yellow = Core()
            request.session['runId'] = yellow.yellowlab(url)
            print(request.session['runId'])
            print(request)

            return render(request, 'yshowresult.html', locals())
        else:
            message = '请检查填写的内容！'
            return render(request, 'yshow.html', locals())
    else:
        message = '测试失败请稍后重试！'
        return render(request, 'yshow.html', locals())


def yellowlab(request):
    message = '例子url：https://www.douchacha.com/'
    pass
    return render(request, 'yshow.html', locals())


# 第一排第二个
# 测试接口自动化列表
def Test_interface_automation(request):
    TestInterfaceList = Test_Interface_List.objects.all()

    if request.GET.get('entry_name') or request.GET.get('entry_name') or request.GET.get(
            'Iterative_version') or request.GET.get('modular') or request.GET.get('case_name'):
        entry_name = request.GET.get('entry_name')
        Iterative_version = request.GET.get('Iterative_version')
        modular = request.GET.get('modular')
        case_name = request.GET.get('case_name')
        caseapi_return = {
            "code": '',
            "msg": '',
            "equipment": {
            }
        }
        for index in range(len(TestInterfaceList)):
            caseapi_return['equipment'][str(index)] = {
                'id': TestInterfaceList[index].id,
                'entry_name': TestInterfaceList[index].entry_name,
                'Iterative_version': TestInterfaceList[index].Iterative_version,
                'modular': TestInterfaceList[index].modular,
                'case_name': TestInterfaceList[index].case_name,
            }
        print("*" * 50)
        print(caseapi_return)
        print("*" * 50)
        entry_name_list = []
        Iterative_version_list = []
        modular_list = []
        case_name_list = []
        for i in range(len(caseapi_return['equipment'])):
            entry_name_list.append(caseapi_return['equipment'][str(i)]['entry_name'])
            Iterative_version_list.append(caseapi_return['equipment'][str(i)]['Iterative_version'])
            modular_list.append(caseapi_return['equipment'][str(i)]['modular'])
            case_name_list.append(caseapi_return['equipment'][str(i)]['case_name'])

        if entry_name == '' and Iterative_version == '' and modular == '' and case_name == '':
            TestInterfaceList = Test_Interface_List.objects.all()
            return render(request, 'Test_interface_automation.html', {'TestInterfaceList': TestInterfaceList})
        elif entry_name != '' and Iterative_version == '' and modular == '' and case_name == '':
            if entry_name in entry_name_list:
                return render(request, 'Test_interface_automation.html', {
                    'TestInterfaceList_search': ast.literal_eval(re.search('({.+})', json.dumps(
                        caseapi_return['equipment'][str(entry_name_list.index(entry_name))])).group(0))})
            else:
                return HttpResponse(
                    '没有你搜索的内容，赶紧添加去吧！' + '<button style="width: 60px;height: 38px; border: 1px solid #1E90FF; border-radius:4px; color: #1E90FF;background-color: #ffffff">        <a class="btn btn-outline-primary" href="/polls/Test_interface_automation">返回</a>    </button>    <button style="width: 60px;height: 38px; border: 1px solid #1E90FF; border-radius:4px; color: #1E90FF;background-color: #ffffff">        <a class="btn btn-outline-primary" href="/polls/test_interface_automation_content" rel="external nofollow">新建</a></button>')
        elif entry_name == '' and Iterative_version != '' and modular == '' and case_name == '':
            if Iterative_version in Iterative_version_list:
                return render(request, 'Test_interface_automation.html', {
                    'TestInterfaceList_search': ast.literal_eval(
                        re.search('({.+})', json.dumps(
                            caseapi_return['equipment'][str(Iterative_version_list.index(Iterative_version))])).group(
                            0))})
            else:
                return HttpResponse(
                    '没有你搜索的内容，赶紧添加去吧！' + '<button style="width: 60px;height: 38px; border: 1px solid #1E90FF; border-radius:4px; color: #1E90FF;background-color: #ffffff">        <a class="btn btn-outline-primary" href="/polls/Test_interface_automation">返回</a>    </button>    <button style="width: 60px;height: 38px; border: 1px solid #1E90FF; border-radius:4px; color: #1E90FF;background-color: #ffffff">        <a class="btn btn-outline-primary" href="/polls/test_interface_automation_content" rel="external nofollow">新建</a></button>')
        elif entry_name == '' and Iterative_version == '' and modular != '' and case_name == '':
            if modular in modular_list:
                return render(request, 'Test_interface_automation.html', {
                    'TestInterfaceList_search': ast.literal_eval(
                        re.search('({.+})',
                                  json.dumps(caseapi_return['equipment'][str(modular_list.index(modular))])).group(0))})
            else:
                return HttpResponse(
                    '没有你搜索的内容，赶紧添加去吧！' + '<button style="width: 60px;height: 38px; border: 1px solid #1E90FF; border-radius:4px; color: #1E90FF;background-color: #ffffff">        <a class="btn btn-outline-primary" href="/polls/Test_interface_automation">返回</a>    </button>    <button style="width: 60px;height: 38px; border: 1px solid #1E90FF; border-radius:4px; color: #1E90FF;background-color: #ffffff">        <a class="btn btn-outline-primary" href="/polls/test_interface_automation_content" rel="external nofollow">新建</a></button>')
        elif entry_name == '' and Iterative_version == '' and modular == '' and case_name != '':
            if case_name in case_name_list:
                return render(request, 'Test_interface_automation.html', {
                    'TestInterfaceList_search': ast.literal_eval(
                        re.search('({.+})',
                                  json.dumps(caseapi_return['equipment'][str(case_name_list.index(case_name))])).group(
                            0))})
            else:
                return HttpResponse(
                    '没有你搜索的内容，赶紧添加去吧！' + '<button style="width: 60px;height: 38px; border: 1px solid #1E90FF; border-radius:4px; color: #1E90FF;background-color: #ffffff">        <a class="btn btn-outline-primary" href="/polls/Test_interface_automation">返回</a>    </button>    <button style="width: 60px;height: 38px; border: 1px solid #1E90FF; border-radius:4px; color: #1E90FF;background-color: #ffffff">        <a class="btn btn-outline-primary" href="/polls/test_interface_automation_content" rel="external nofollow">新建</a></button>')
    else:
        return render(request, 'Test_interface_automation.html', {'TestInterfaceList': TestInterfaceList})


# 删除数据
def delete_interface(request):
    if request.method == 'GET':
        List_id = request.GET.get('list_id')
        gp = Test_Interface_List.objects.filter(id=List_id)
        if len(gp) == 0:
            return HttpResponse('兄弟你在逗我玩,根本没有这个ID数据！')
        else:
            delete_list_content = Test_Interface_List_Content.objects.filter(Association_id=List_id)
            delete_list_content.delete()
            delete_list = Test_Interface_List.objects.get(id=List_id)
            delete_list.delete()
            return HttpResponse('已成功删除')

    return render(request, 'test_interface_automation.html')


# 测试接口自动化添加页面
def test_interface_automation_content(request):
    id = request.GET.get('id')
    if request.GET.get('id'):
        Render_details_list = {}
        interface_list = Test_Interface_List.objects.filter(id=id)
        interface_list_content = Test_Interface_List_Content.objects.filter(Association_id=id)
        for i in interface_list:
            Render_details_list['id'] = i.id
            Render_details_list['entry_name'] = i.entry_name
            Render_details_list['Iterative_version'] = i.Iterative_version
            Render_details_list['modular'] = i.modular
            Render_details_list['case_name'] = i.case_name

        for i in interface_list_content:
            Render_details_list['User_id'] = i.User_id
            Render_details_list['url'] = i.url
            Render_details_list['Token'] = i.Token
            Render_details_list['Request_type'] = i.Request_type
            Render_details_list['Body'] = i.Body
            Render_details_list['Headers'] = i.Headers
            # Render_details_list['Transmission_parameters'] = i.Transmission_parameters
            # Render_details_list['Calibration_parameters'] = i.Calibration_parameters
            # Render_details_list['Replace_parameter'] = i.Replace_parameter
            Render_details_list['not_in_null'] = i.not_in_null

        return render(request, 'test_interface_automation_content.html', locals())
    return render(request, 'test_interface_automation_content.html')


# 获取token
def get_token(request):
    if request.method == 'POST':
        account_number = request.POST.get('account_number')
        password = request.POST.get('password')
        url = "https://api.test.douchacha.com/api/user/login?sign=df-dcc"
        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "close",
            "Content-Length": "77",
            "Content-Type": "application/json;charset=UTF-8",
            "d-t": str(int(time.time() * 1000)),
            "dcc-href": "https://test.douchacha.com/",
            "dcc-r": "https://test.douchacha.com/",
            "Host": "api.test.douchacha.com",
            "Origin": "https://test.douchacha.com",
            "Pragma": "no-cache",
            "Referer": "https://test.douchacha.com/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-site",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36",
        }
        data = {
            "phone": str(account_number),
            "password": sha1(password.encode('utf8')).hexdigest(),
        }
        Response = requests.post(url=url, headers=headers, data=json.dumps(data), proxies=proxies, verify=False)
        res_token = json.loads(Response.text)
        if '密码错误' in res_token['msg']:
            return HttpResponse(300)
        else:
            return HttpResponse(res_token["data"]["token"])


def Test_verification(request):
    if request.method == 'POST':
        User_id = request.POST.get('User_id')
        url = request.POST.get('url')
        Token = request.POST.get('Token')
        Request_type = request.POST.get('Request_type')
        Body = request.POST.get('Body')
        Headers = request.POST.get('Headers')
        # Transmission_parameters = request.POST.get('Transmission_parameters')
        # Calibration_parameters = request.POST.get('Calibration_parameters')
        # Replace_parameter = request.POST.get('Replace_parameter')
        not_in_null = request.POST.get('not_in_null')
        print('*' * 50)
        print("User_id: ", User_id)
        print("url: ", url)
        print("Token: ", Token)
        print("Request_type: ", Request_type)
        print("Body: ", Body)
        print("Headers: ", Headers)
        # print("Transmission_parameters: ", Transmission_parameters)
        # print("Calibration_parameters: ", type(Calibration_parameters), Calibration_parameters)
        # print("Replace_parameter: ", Replace_parameter)
        print("not_in_null: ", not_in_null)
        print('*' * 50)
        if "Token" in Headers:
            Headers = Headers.replace("Token", Token)
        elif "token" in Headers:
            Headers = Headers.replace("token", Token)
        if 'd-t' in Headers:
            Headers = Headers.replace('时间戳', str(round(time.time() * 1000)))
        if Request_type == 'POST' or Request_type == 'post':
            Response = requests.post(url=url, headers=json.loads(Headers), data=json.dumps(json.loads(Body)),
                                     proxies=proxies,
                                     verify=False)
            req = json.loads(Response.text)
            not_in_null_dict = ast.literal_eval(re.search('({.+})', not_in_null).group(0))

            if "请先登录账号" in req['msg']:
                return HttpResponse('token失效，需要获取新的token在进行使用')
            else:
                if 'data' not in req:
                    return HttpResponse('兄弟啊，咱们的接口现在有问题啊' + str(req))
                else:
                    if req['data'] != not_in_null_dict['data']:
                        return HttpResponse(str(req))
                    else:
                        return HttpResponse('接口没错,请求没错,就是没有数据' + str(req))

        else:
            Response = requests.get(url=url, headers=json.loads(Headers), proxies=proxies, verify=False)
            req = json.loads(Response.text)
            not_in_null_dict = ast.literal_eval(re.search('({.+})', not_in_null).group(0))

            if "请先登录账号" in req['msg']:
                return HttpResponse('token失效，需要获取新的token在进行使用')
            else:
                if 'data' not in req:
                    return HttpResponse('兄弟啊，咱们的接口现在有问题啊' + str(req))
                else:
                    if req['data'] != not_in_null_dict['data']:
                        return HttpResponse(str(req))
                    else:
                        return HttpResponse('接口没错,请求没错,就是没有数据' + str(req))


# 保存数据
def preservation_interface(request):
    if request.method == 'POST':
        updata = request.POST.get('updata')
        id = request.POST.get('id')
        entry_name = request.POST.get('entry_name')
        Iterative_version = request.POST.get('Iterative_version')
        modular = request.POST.get('modular')
        case_name = request.POST.get('case_name')
        User_id = request.POST.get('User_id')
        url = request.POST.get('url')
        Token = request.POST.get('Token')
        Request_type = request.POST.get('Request_type')
        Body = request.POST.get('Body')
        Headers = request.POST.get('Headers')
        # Transmission_parameters = request.POST.get('Transmission_parameters')
        # Calibration_parameters = request.POST.get('Calibration_parameters')
        # Replace_parameter = request.POST.get('Replace_parameter')
        not_in_null = request.POST.get('not_in_null')
        if len(id) < 1 or len(entry_name) < 1 or len(Iterative_version) < 1 or len(modular) < 1 or len(
                case_name) < 1:
            return HttpResponse('你想干啥？？？不填写id、项目、版本、模块、case, 我怎么给你存储数据？')
        elif len(url) < 1 or len(Headers) < 1 or len(Token) < 1 or len(Request_type) < 1:
            return HttpResponse('搞什么呢url和headers都不填等我填呢？Token与类型也是必填！')
        elif len(Body) < 1 or len(Headers) < 1:
            return HttpResponse('body与Headers不填写我怎么给你请求接口？？？完蛋去吧！！！')
        # elif len(Calibration_parameters) < 1:
        #     return HttpResponse('检查参数不填你让我测啥！')
        save_list = Test_Interface_List()
        save_content = Test_Interface_List_Content()

        # 更新case
        if updata == str(111):
            delete_list_content = Test_Interface_List_Content.objects.filter(Association_id=id)
            delete_list_content.delete()

            save_content.User_id = User_id
            save_content.url = url
            save_content.Token = Token
            save_content.Request_type = Request_type
            save_content.Body = Body
            save_content.Headers = Headers
            # save_content.Transmission_parameters = Transmission_parameters
            # save_content.Calibration_parameters = Calibration_parameters
            # save_content.Replace_parameter = Replace_parameter
            save_content.not_in_null = not_in_null
            save_content.Association_id = id
            save_content.save()
            return HttpResponse("case已更新")  # 保存成功给用户提示’
        else:
            save_list.id = id
            save_list.entry_name = entry_name
            save_list.Iterative_version = Iterative_version
            save_list.modular = modular
            save_list.case_name = case_name
            save_list.save()

            save_content.User_id = User_id
            save_content.url = url
            save_content.Token = Token
            save_content.Request_type = Request_type
            save_content.Body = Body
            save_content.Headers = Headers
            # save_content.Transmission_parameters = Transmission_parameters
            # save_content.Calibration_parameters = Calibration_parameters
            # save_content.Replace_parameter = Replace_parameter
            save_content.not_in_null = not_in_null
            save_content.Association_id = id
            save_content.save()
            return HttpResponse("case已保存")  # 保存成功给用户提示’

    return render(request, 'test_interface_automation_content.html')


# 第二排第一个
# 接口性能压测
def locust_start(request):
    print("************************************************************************")
    url = request.GET.get('url')
    token = request.GET.get('token')
    print(url, token)
    print("************************************************************************")
    if token != '':
        a = """
import math

from locust import task, between, SequentialTaskSet, events, HttpUser, LoadTestShape


class AppUsers(SequentialTaskSet):

    def on_start(self):
        print('----------开始执行子任务---------')

    def on_stop(self):
        print('---------结束执行子任务----------')
        print('\\n')
        """
        a1 = """

header = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, br",
    "authorization": "%s"
        }

        """ % token
        a2 = """
@task
def index_2(self):
    with self.client.get(
            "%s",
            headers=self.header, catch_response=True,
            name='index_2') as response:
        if response.status_code != 200:
            response.failure('请求出问题了')
    print('index_2:', response.status_code)
        """ % url
        a3 = """
    #
    # @task
    # def index_3(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/trend?searchTypes=IN_LIVE_NUMBER&searchTypes=LEAVE_LIVE_NUMBER&searchTypes=ON_LINE_NUMBER&warningType=IN_LIVE_NUMBER_UP&warningType=IN_LIVE_NUMBER_DOWN&warningType=COMMENT_NUMBER_DOWN&warningType=IN_LIVE_NUMBER&markPoints=true&warnPoints=true&timeType=MINUTE&pointsType=ADD_GOODS',
    #             headers=self.header, catch_response=True,
    #             name='index_3') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_3:', response.status_code)
    #
    # @task
    # def index_4(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/flow_source',
    #             headers=self.header, catch_response=True,
    #             name='index_4') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_4:', response.status_code)
    #
    # @task
    # def index_5(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/flow_trans',
    #             headers=self.header, catch_response=True,
    #             name='index_5') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_5:', response.status_code)
    #
    # @task
    # def index_6(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/comments?current=1&size=50',
    #             headers=self.header, catch_response=True,
    #             name='index_6') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_6:', response.status_code)
    #
    # @task
    # def index_7(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/goods?current=1&size=10',
    #             headers=self.header, catch_response=True,
    #             name='index_7') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_7:', response.status_code)

    @task
    def stop(self):
        self.interrupt()


class StepLoadShaper(LoadTestShape):
    setp_time = 100
    setp_load = 1000
    spawn_rate = 10
    time_limit = 100

    def tick(self):
        run_time = self.get_run_time()

        if run_time > self.time_limit:
            return None

        current_step = math.floor(run_time / self.setp_time) + 1

        return current_step * self.setp_load, self.spawn_rate


class NewLinkToG(HttpUser):  # 模拟App用户
    # abstract = True   跳过执行该类
    # host = 'https://api.test.dylive.aiyingli.com'
    host = ''
    wait_time = between(10, 15)  # taskset类中每个def的执行间隔
    tasks = [AppUsers]


@events.test_start.add_listener
def on_test_start(**kwargs):  # 监测测试开始
    print('开始执行')


@events.test_stop.add_listener
def on_test_stop(environment, **kwargs):  # 监测测试结束
    print('执行结束')


@events.request_success.add_listener
def request_success(request_type, name, response_time, response_length, **kwargs):  # 监测请求成功
    result = 'success'
    print("{" + "'message':'{result}' ".format(
        result=result) + "'request_type':'{}','name':'{}','response_time':'{}','response_length':'{}'".format(
        request_type, name, response_time, response_length) + " }")


@events.request_failure.add_listener
def request_failure(request_type, name, response_time, response_length, **kwargs):  # 监测请求失败
    result = 'failure'
    print("{" + "'message':'{result}' ".format(
        result=result) + "'request_type':'{}','name':'{}','response_time':'{}','response_length':'{}'".format(
        request_type, name, response_time, response_length) + " }")


@events.quitting.add_listener
def _(environment, **kw):
    if environment.stats.total.fail_ratio > 0.01:
        print("Test failed due to failure ratio > 1%")
        environment.process_exit_code = 1
    elif environment.stats.total.avg_response_time > 200:
        print("Test failed due to average response time ratio > 200 ms")
        environment.process_exit_code = 1
    elif environment.stats.total.get_response_time_percentile(0.95) > 800:
        print("Test failed due to 95th percentile response time > 800 ms")
        environment.process_exit_code = 1
    else:
        environment.process_exit_code = 0


if __name__ == '__main__':
    import os

    os.system('locust -f locust-1.py')  # 主机
        """

        aa = a + a1 + a2 + a3
        with open("locust.py", mode="w+", encoding="utf-8") as f:
            f.write(aa)
        time.sleep(3)
        str1 = 'python C:/Users/admin/Desktop/dcc/untitled/polls/locust.py'
        os.system(str1)
        time.sleep(3)

    return render(request, 'locust_dcc_A.html', locals())


def locust_implement(request):
    return render(request, 'locust_dcc_A.html', locals())


# 第二排第三个
# app测试
@csrf_exempt
def app_case(request):
    if request.method == 'POST':
        msg = {'code': '', 'msg': ''}
        app = request.FILES.get("file", None)
        applist = request.POST.get('appidlist', None)
        activityname = request.POST.get('activityname_z', None)
        appname = request.POST.get('app_name', None)
        if app != None:
            with open(os.path.join(settings.app_z, app.name), "wb") as f:
                for chunk in app.chunks():
                    f.write(chunk)
        else:
            t_list = []  # 线程列表
            dog(json.loads(applist), appname, activityname)
            return render(request, 'app_index.html', locals())
        return render(request, 'app_index.html', locals())
    else:
        appall = getDevicesAll()
        return render(request, 'app_index.html', locals())

# # APP结果分析
# @csrf_exempt
# @ensure_csrf_cookie
# def case_app_report(request):
#     case = {
#         0: {
#             'key': 'KZYTINT449YSPZRC_1608549445',
#             'Mobile_phone_brands': 'Xiaomi',
#             'phone_brands_version': 'MIX 3',
#             'Android_version': '10',
#             'phone_px': '1080x2340',
#             'phone_code': 'c35b737c',
#
#             'Install': 'True',
#             'Uninstall': 'False',
#             'time_c': '',
#             'time_h': '',
#
#             'Collapse': 'False',
#             'Test_time': '开始时间减去脚本结束时间',
#             'Data_time': '当天时间戳',
#             'phone_d': '应用耗电量',
#             'cpu': {'时间每5秒获取一次': '数值'},
#             'phone_f': {'时间每5秒获取一次': '数值'},
#             'log_name': '地址',
#             'phone_video': '地址',
#         },
#         1: {
#             'key': 'KZYTINT449YSPZRC_1608549445',
#             'Mobile_phone_brands': 'Xiaomi',
#             'phone_brands_version': 'MIX 3',
#             'Android_version': '10',
#             'phone_px': '1080x2340',
#             'phone_code': 'c35b737c',
#             'Install': 'False',
#             'Uninstall': 'True',
#             'time_c': '',
#             'time_h': '',
#             'Collapse': 'False',
#             'Test_time': '开始时间减去脚本结束时间',
#             'Data_time': '当天时间戳',
#             'phone_d': '应用耗电量',
#             'cpu': {'时间每5秒获取一次': '数值'},
#             'phone_f': {'时间每5秒获取一次': '数值'},
#             'log_name': '地址',
#             'phone_video': '地址',
#         }
#     }
#     if request.method == 'POST':
#         # -----------------批量获取上传-----------------------------
#         filelog = request.FILES.getlist("filelog", None)
#         filephoto = request.FILES.getlist("filephoto", None)
#         filemp4 = request.FILES.getlist("filemp4", None)
#         bugreport = request.POST.get('bugreport', None)
#         pngname, logname, mp4name = [], [], []
#         # ----------------------------------------------------
#         if filelog != None and bugreport != None and filephoto != None and filemp4 != None:
#             # try:
#             phone, android_version, install, uninstall, Collapse = [], [], [], [], []
#             Data_time = None
#             scriptlist = bugreport
#             Phone_count = len(eval(bugreport))
#             phone_status = 0
#             report = eval(bugreport)
#             report_key = None
#             phone_px = []
#             time_h = [[], []]
#             time_c = [[], []]
#             phone_cpu = [[], []]
#             phone_dumpsys = [[], []]
#             apppng = settings.BASE_DIR + '/polls/static/app_png/'
#             applog = settings.BASE_DIR + '/polls/static/app_log/'
#             appmp4 = settings.BASE_DIR + '/polls/static/app_mp4/'
#             # -----------------批量上传文件保存----------------------------
#             for filelog_value in filelog:
#                 logname.append(filelog_value.name)
#                 with open(os.path.join(applog, filelog_value.name), "wb") as f:
#                     for chunk in filelog_value.chunks():
#                         f.write(chunk)
#             # -----------------压缩文件----------------------------
#             for filephotovalue in filephoto:
#                 pngname.append(filephotovalue.name)
#                 with open(os.path.join(apppng, filephotovalue.name), "wb") as f:
#                     for chunk in filephotovalue.chunks():
#                         f.write(chunk)
#             for pngnamevalue in pngname:
#                 # 打开图片
#                 image = Image.open(os.path.join(apppng, pngnamevalue))
#                 # 缩小
#                 # 图片对象.thumbnail(大小) - 按比例缩放
#                 image_w, image_h = image.size
#                 image.thumbnail((image_w / 4, image_h / 4))
#                 # image.show()
#                 image.save(os.path.join(apppng, pngnamevalue))
#             for filemp4value in filemp4:
#                 mp4name.append(filemp4value.name)
#                 with open(os.path.join(appmp4, filemp4value.name), "wb") as f:
#                     for chunk in filemp4value.chunks():
#                         f.write(chunk)
#             log_name = []
#             Causedby_list = []
#             Causedby_count = 0
#
#             for key in report:
#                 log_name.append(report[key]['log_name'])
#                 case_status = None
#                 cpu = []
#                 dumpsys = []
#                 phone.append(report[key]['Mobile_phone_brands'])
#                 Causedby = []
#                 Causedby_list_value = 0
#                 # -----------------app日志分析----------------------------
#                 f = open(os.path.join(applog, str(report[key]['log_name']) + '.txt'), 'r+')
#                 for line in f.readlines():  # 这样写的效果就是逐行读取文件中的内容，并且内存中始终仅保存读取的这一行内容 此时的f是一个迭代器
#
#                     if 'Caused by' in line:
#                         Causedby.append(line)
#                         Causedby_count = Causedby_count + 1
#                         Causedby_list_value = Causedby_list_value + 1
#                         case_status = False
#
#                     if 'Force finish' in line:
#                         Causedby.append(line)
#                         Causedby_count = Causedby_count + 1
#                         Causedby_list_value = Causedby_list_value + 1
#                         case_status = False
#
#                     if 'ANR' in line:
#                         Causedby.append(line)
#                         Causedby_count = Causedby_count + 1
#                         Causedby_list_value = Causedby_list_value + 1
#                         case_status = False
#                 Causedby_list.append(Causedby_list_value)
#
#                 f.close()
#                 # -----------------app 有问题就判断测试不通过----------------------------
#                 if report[key]['install'] == 'False':
#                     install.append(report[key]['install'])
#
#                     case_status = False
#                 if report[key]['uninstall'] == 'False':
#                     uninstall.append(report[key]['uninstall'])
#
#                     case_status = False
#
#                 if case_status == False:
#                     android_version.append(report[key]['Android_version'])
#                     phone_px.append(report[key]['phone_px'])
#                     phone_status = phone_status + 1
#                 # -----------------app 冷启动热启动处理----------------------------
#                 Data_time = report[key]['Data_time']
#                 time_h[0].append(float(report[key]['time_h']))
#                 time_h[1].append(str(report[key]['phone_brands_version']) + str(report[key]['Mobile_phone_brands']))
#                 time_c[0].append(float(report[key]['time_c']))
#                 time_c[1].append(str(report[key]['phone_brands_version']) + str(report[key]['Mobile_phone_brands']))
#
#                 app_report_key = report[key]['key']
#                 for value in report[key]['cpu'].values():
#                     cpu.append(float(value))
#                 phone_cpu[0].append(sorted(list(cpu), reverse=True)[0])
#                 phone_cpu[1].append(str(report[key]['phone_brands_version']) + str(report[key]['Mobile_phone_brands']))
#
#                 for value in report[key]['dumpsys'].values():
#                     dumpsys.append(float(value))
#
#                 phone_dumpsys[0].append(sorted(list(dumpsys), reverse=True)[0])
#                 phone_dumpsys[1].append(
#                     str(report[key]['phone_brands_version']) + str(report[key]['Mobile_phone_brands']))
#
#             # -----------------综合报告存入缓存----------------------------
#             statistical = {
#                 'key': app_report_key,
#                 'Mobile_phone_brands_count': str(len(phone)),
#                 'Mobile_phone_brands': str(phone),
#                 'Android_version_count': str(len(android_version)),
#                 'Android_version': android_version,
#                 'Install_count': str(len(install)),
#                 'Install_z': str(len(install) / len(phone) * 100) + '%',
#                 'Uninstall_z': str(len(uninstall) / len(phone) * 100) + '%',
#                 'Uninstall_count': str(len(uninstall)),
#                 'Collapse_count': 0,
#                 'Data_time': str(Data_time),
#                 'scriptlist': eval(bugreport),
#                 'phone_status': str(phone_status),
#                 'phone_statu_z': str(phone_status / len(phone) * 100) + '%',
#                 'phone_px': str(phone_px),
#                 'time_h': time_h,
#                 'time_h_sorted': sorted(time_h[0], reverse=True)[0],
#                 'time_c': time_c,
#                 'time_c_sorted': sorted(time_c[0], reverse=True)[0],
#                 'phone_cpu': phone_cpu,
#                 'phone_cpu_sorted': sorted(phone_cpu[0], reverse=True)[0],
#                 'phone_dumpsys': phone_dumpsys,
#                 'phone_dumpsys_sorted': sorted(phone_dumpsys[0], reverse=True)[0],
#                 'pngname': pngname,
#                 'logname': logname,
#                 'mp4name': mp4name,
#                 'Causedby_count': str(Causedby_count),
#                 'Causedby_list': Causedby_list
#             }
#             appreport_key = app_report_key
#             cache.set(appreport_key, case, timeout=86400)
#             # cache.set(appreport_key, statistical, timeout=86400)
#             # settings.URL+'polls/case_app_report/?appreport_key='+appreport_key
#             # -----------------保存进入报告列表----------------------------
#             report_list = models.report_list()
#             report_list.reportkey = appreport_key
#             report_list.reportname = appreport_key
#             report_list.reportclass = 'app测试'
#             report_list.save()
#             report = models.report_list.objects.all()
#             reportlistrediskey = "reportlist"
#             cache.set(reportlistrediskey, report, timeout=86400)
#
#             # 'http://39.105.45.46/polls/case_app_report/?appreport_key=KZYTINT449YSPZRC_1608813618'
#             # caseapi_return = {
#             #     'code': '200',
#             #     'msg': settings.URL + 'polls/case_app_report/?appreport_key=' + appreport_key
#             # }
#             # return HttpResponse(json.dumps(caseapi_return))
#         # except:
#         #     caseapi_return = {
#         #         'code': '404',
#         #         'msg': '不知道哪错了'
#         #     }
#         #     return HttpResponse(json.dumps(caseapi_return))
#         #
#         # else:
#         #     caseapi_return = {
#         #         'code': '404',
#         #         'msg': '搞什么搞'
#         #     }
#         #     return HttpResponse(json.dumps(caseapi_return))
#     else:
#         caseapi_return = {
#             "code": '',
#             "msg": '',
#             "equipment": {
#                 # 0: {
#                 #     'phonevendorname': '111111',
#                 #     'phoneequipmentname': '222222',
#                 #     'phoneserialnumber': '333333',
#                 #     'phone_state': '4444444',
#                 # },
#             }
#         }
#         error = ''
#         appreport_key = request.GET.get('appreport_key', None)
#         appreport = cache.get(appreport_key)
#
#         if appreport == None:
#             caseapi_return = {
#                 'code': '200',
#                 'msg': '报告不存在了'
#             }
#             return HttpResponse(json.dumps(caseapi_return))
#         value = request.GET.get('value', None)
#         if value != None:
#             # print(appreport)
#             # -----------------------------------app机型详情页-----------------------------
#             Install_count = appreport['Install_count']
#             Uninstall_count = appreport['Uninstall_count']
#
#             script = appreport['scriptlist'][value]
#             Causedby = appreport['Causedby_list'][int(value)]
#             # Collapse_count = script['Collapse']
#             phone_status = None
#             pngname = []
#             logname = script['log_name']
#             videoname = settings.URL + 'static/app_mp4/' + script['phone_video']
#             apppng = settings.BASE_DIR + '/polls/static/app_png/'
#             for value in script['screenshot'].values():
#                 pngname.append(settings.URL + 'static/app_png/' + value)
#
#             cpu_y = list(script['cpu'].values())
#             phone_cpu_sorted = sorted(cpu_y, reverse=True)[0]
#             cpu_x = list(script['cpu'].keys())
#
#             dumpsys_y = script['dumpsys'].values()
#             dumpsys_x = list(script['dumpsys'].keys())
#             phone_dumpsys_sorted = sorted(dumpsys_y, reverse=True)[0]
#
#             error = ''
#             if script['install'] == 'False':
#                 phone_status = '未通过'
#                 error = error + '安装失败、'
#             if script['uninstall'] == 'False':
#                 phone_status = '未通过'
#                 error = error + '卸载失败、'
#             if Causedby > 0:
#                 phone_status = '未通过'
#                 error = error + 'Crash、报错、无响应'
#             return render(request, 'app_log_index.html', locals())
#         else:
#             # -----------------------------------app兼容性能测试总页面-----------------------------
#             Mobile_phone_brands_count = appreport['Mobile_phone_brands_count']
#             Mobile_phone_brands = appreport['Mobile_phone_brands']
#             Android_version_count = appreport['Android_version_count']
#             Android_version = appreport['Android_version']
#             Install_count = appreport['Install_count']
#             Install_z = appreport['Install_z']
#             Uninstall_z = appreport['Uninstall_z']
#             Uninstall_count = appreport['Uninstall_count']
#             Collapse_count = appreport['Causedby_count']
#             Data_time = appreport['Data_time']
#             scriptlist = appreport['scriptlist']
#             phone_status = appreport['phone_status']
#             phone_error_z = int(phone_status) / int(Mobile_phone_brands_count) * 100
#             phone_pass_z = 100 - phone_error_z
#             phone_px = appreport['phone_px']
#             Data_time = appreport['Data_time']
#             phone_statu_z = appreport['phone_statu_z']
#             time_h_y = appreport['time_h'][0]
#             time_h_x = appreport['time_h'][1]
#
#             time_c_y = appreport['time_c'][0]
#             time_c_x = appreport['time_c'][1]
#
#             phone_dumpsys_y = appreport['phone_dumpsys'][0]
#             phone_dumpsys_x = appreport['phone_dumpsys'][1]
#
#             time_h_sorted = appreport['time_h_sorted']
#             time_c_sorted = appreport['time_c_sorted']
#             phone_dumpsys_sorted = appreport['phone_dumpsys_sorted']
#
#             phone_cpu = appreport['phone_cpu']
#             phone_cpu_y = appreport['phone_cpu'][0]
#             phone_cpu_x = appreport['phone_cpu'][1]
#             phone_cpu_sorted = appreport['phone_cpu_sorted']
#
#             for index in scriptlist.keys():
#                 caseapi_return['equipment'][index] = {
#                     'Mobile_phone_brands': str(scriptlist[index]['Mobile_phone_brands']) + str(
#                         scriptlist[index]['phone_brands_version']),
#                     'go': index
#                 }
#             if int(Collapse_count) > 0:
#                 error = error + 'Crash、无响应、'
#             if int(Uninstall_count) > 0:
#                 error = error + '卸载失败、'
#             if int(Install_count) > 0:
#                 error = error + '安装失败、'
#             return render(request, 'app_log.html', locals())
#             pass
#
#
# @csrf_exempt
# @ensure_csrf_cookie
# def app_report(request):
#     if request.method == 'POST':
#         return render(request, 'app_log.html', locals())
#     else:
#
#         return render(request, 'app_log.html', locals())
#
#
# @csrf_exempt
# @ensure_csrf_cookie
# def applog_download(request):
#     if request.method == "POST":
#         pass
#     else:
#         logname = request.GET.get('logname', None)
#         applogpath = settings.BASE_DIR + '/polls/static/app_log/' + logname + '.txt'
#         file = open(applogpath, 'rb')
#         response = HttpResponse(file)
#         response['Content-Type'] = 'application/octet-stream'  # 设置头信息，告诉浏览器这是个文件
#         filename = logname + '.txt'
#         print('attachment;filename="%s"' % filename)
#         response['Content-Disposition'] = 'attachment;filename="%s"' % filename
#         return response
